package com.mrwang.example.nio.part20191027;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.*;

public class MyChatServer {
    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8899));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        Map<SocketChannel, String> clientMap = new HashMap<SocketChannel, String>();

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    System.out.println("客户端已经连接 b：" + client);
                    String key = UUID.randomUUID().toString();
                    clientMap.put(client, "[" + key + "]:");
                    client.register(selector, SelectionKey.OP_READ);

                    iterator.remove();
                } else if (selectionKey.isReadable()) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    ByteBuffer bb = ByteBuffer.allocate(1024);
                    int read = client.read(bb);
                    if (read > 0) {
                        String userId = clientMap.get(client);
                        bb.flip();
                        String message = String.valueOf(Charset.forName("UTF-8").decode(bb).array());
                        System.out.println("client id :" + userId + ",messageReceiver:" + message);
                        String response = userId + message;

                        for (Map.Entry<SocketChannel, String> entry : clientMap.entrySet()) {

                            ByteBuffer writeByte = ByteBuffer.allocate(1024);

                            SocketChannel socketChannel = entry.getKey();

                            writeByte.put(response.getBytes());
                            writeByte.flip();
                            socketChannel.write(writeByte);
                        }
                    }
                    iterator.remove();
                }
            }
        }
    }
}
